package com.qiyang.contoller;

import com.qiyang.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;

@Controller
public class HomeController {

    /**
     * 自动映射参数，自动类型转换，默认参数名与方法参数名一致
     * @RequestParam注解可以重命名参数名称，用此注解默认必须传入值
     * required 可设置是否必须传入，默认为true
     * 注意不能使用基础类型接收，不传则会报错，所以最好用包装类型接，能够接null
     * defaultValue 默认值，此时可省略 required 参数
     * @param name
     * @return
     */
    @RequestMapping("/home")
    public String home(@RequestParam(value = "name", required = false, defaultValue = "none") String name) {

        System.out.println("name is " + name);

        return "index.jsp";
    }

    @GetMapping("/params01")
    public String toForm() {

        return "params.jsp";
    }

    /**
     * 复杂数据类型处理
     * GET 若乱码，设置Tomcat Server.xml Connector URLEncoding="UTF-8"
     * POST 参数乱码：设置Request编码,每个地方都要处理 | 添加过滤器解决 | 使用SpringMVC提供
     * 如果接收的参数对象，有多个，不好意思，那就再封装一层DTO
     * @param user
     * @return
     */
    @PostMapping("/params01")
    public String submitForm(User user) {

        System.out.println("name is " + user);

        return "index.jsp";
    }

    /**
     * 获取请求头信息
     * @param host
     * @return
     */
    @RequestMapping("/header")
    public String header(@RequestHeader(value = "Host")String host) {

        System.out.println("host is " + host);

        return "index.jsp";
    }

    /**
     * 获取cookie
     * 获取所有cookie 将参数类型定义为map就行
     * @param sessionId
     * @return
     */
    @RequestMapping("/cookie")
    public String cookie(@CookieValue(value = "JSESSIONID")String sessionId) {

        System.out.println("sessionId is " + sessionId);

        return "index.jsp";
    }

//    /**
//     * HttpServletRequest
//     * HttpServletResponse
//     * HttpSession 当前会话
//     * Locale 当前语言
//     * Principal 安全协议
//     * ...
//     * @param request
//     * @param response
//     * @return
//     */
//    @RequestMapping("/servlet")
//    public String servlet(HttpServletRequest request, HttpServletResponse response) {
//
//        System.out.println("servlet param is " + request.getParameter("name"));
//
//        return "index.jsp";
//    }
}
